import {Component, EventEmitter, Output} from '@angular/core';
import {
    AlertController, App, IonicPage, LoadingController, NavController, NavParams, Platform,
    ToastController
} from 'ionic-angular';
import {SystemService} from "../../service/SystemService";
import {Log} from "../../../framework/utils/Log";
import {BasePage} from "../../BasePage";
import {SLLocalStorageUtils} from "../../../framework/utils/SLLocalStorageUtils";
import {Utils} from "../../../framework/utils/Utils";
import {UserManager} from "../../../framework/manager/UserManager";
import {TabsPage} from "../../tabs/tabs";
import {ApplyStoreSLS} from "../applyStoreSLS";
import {AssistTabPage} from "../assist-tab/assist-tab";

/**
 * Generated class for the CloseAccountTabPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */
@Component({
    selector: 'page-close-account-tab',
    templateUrl: 'close-account-tab.html',
    providers: [SystemService]
})
export class CloseAccountTabPage extends BasePage {
    private static TAG: string = 'CloseAccountTabPage';
    public payWayList: any = [];
    @Output() addBtnShow = new EventEmitter<any>();
    fee: number;
    zzList: Array<any> = [];
    gwkList: Array<any> = [];
    list: Array<any> = [];
    private newCloseWay: any = [];
    private getAssistInfo: any;
    private getApplyInfo: any;
    private getApplyDetails: any;
    private getFileInfo: any;
    private flowList: any = [];
    public appleFee: any = 0;
    public keyongFee: any = 0;
    public sxFee: any;
    public newValFee: any;
    private isNullBool: boolean = false;
    private editBool: boolean;
    private editInfo: any;
    private moneyAppleBool: boolean;
    private moneyAppleInfo: any;
    private isClickBool:boolean =false;
    private isFristBool:boolean=false;
    constructor(public navCtrl: NavController, public app: App, public navParams: NavParams, public sys: SystemService, public platform: Platform,
                public loadingCtrl: LoadingController,
                public toastCtrl: ToastController,
                public alertCtrl: AlertController) {
        super(platform, loadingCtrl, toastCtrl, alertCtrl);
        this.editBool = this.navParams.data.editBool;
        this.editInfo = this.navParams.data.editInfo;
        this.moneyAppleBool = this.navParams.data.moneyAppleBool;
        this.moneyAppleInfo = this.navParams.data.moneyAppleInfo;
        //this.payWayList = JSON.parse(localStorage.getItem('payWayList'));

    }

    ngOnInit() {
        Log.d(CloseAccountTabPage.TAG, 'ngOnInit CloseAccountTabPage');
        this.getAppleInfo();
    }

    async getAppleInfo() {
        if (!Utils.isNullOrUndefined(await SLLocalStorageUtils.getInstance().getAssist())) {
            this.getAssistInfo = await SLLocalStorageUtils.getInstance().getAssist();
        }
        if (!Utils.isNullOrUndefined(await SLLocalStorageUtils.getInstance().getApply())) {
            this.getApplyInfo = await SLLocalStorageUtils.getInstance().getApply();
        }
        if (!Utils.isNullOrUndefined(await SLLocalStorageUtils.getInstance().getApplyDetails())) {
            this.getApplyDetails = await SLLocalStorageUtils.getInstance().getApplyDetails();
        }
        if (!Utils.isNullOrUndefined(await SLLocalStorageUtils.getInstance().getFileInfo())) {
            this.getFileInfo = await SLLocalStorageUtils.getInstance().getFileInfo();
        }
        if (!Utils.isNullOrUndefined(await SLLocalStorageUtils.getInstance().getAppleFee())) {
            this.appleFee = await SLLocalStorageUtils.getInstance().getAppleFee();
            this.newValFee = this.appleFee;
        }
        if (!Utils.isNullOrUndefined(await SLLocalStorageUtils.getInstance().getZbFee())) {
            this.keyongFee = await SLLocalStorageUtils.getInstance().getZbFee();
        }
        if (!Utils.isNullOrUndefined(await SLLocalStorageUtils.getInstance().getAppleSxFee())) {
            this.sxFee = await SLLocalStorageUtils.getInstance().getAppleSxFee();
        }
    }

    ionViewDidEnter() {
        if (ApplyStoreSLS.getInstance().closeAccountList == null) {
            this.getCloseFeeList();

        } else {
            this.list = ApplyStoreSLS.getInstance().closeAccountList;
            this.list.forEach(value => {
                value.feeLabel=this.newValFee;
            });
            this.payWayList = ApplyStoreSLS.getInstance().closeWayList;
            this.zzList = ApplyStoreSLS.getInstance().zzList;
            this.gwkList = ApplyStoreSLS.getInstance().gwkList;
        }
    }
    //资金申请信息
    moneyApplyDataFun(){

        Log.printObj(CloseAccountTabPage.TAG,"资金申请单结算信息====",this.moneyAppleInfo.data.JSFSlist)

        this.moneyAppleInfo.data.JSFSlist.map((v,i)=>{
            this.parameterJson();
            this.list[i].option =v.JieSuanFS;
            this.list[i].feeLabel=v.JieSuanJE;
            this.appleFee =v.JieSuanJE;
            if(v.JieSuanFS=="3"){
                this.list[i].zzLabel[0].Value =v.ShouKuanFZHM;
                this.list[i].zzLabel[1].Value=v.KaiHuH;
                this.list[i].zzLabel[2].Value=v.ZhangHao;
            }
            if(v.JieSuanFS=="4"){
                this.list[i].gwkLabel[0].Value =v.GongWuKH;
                this.list[i].gwkLabel[1].Value=v.XiaoFeiRQ;
                this.list[i].gwkLabel[2].Value=v.JiZhangRQ;
                this.list[i].gwkLabel[3].Value=v.HuanKuanRQ;
                this.list[i].gwkLabel[4].Value=v.BeiZhu;
            }
        });




       /* this.payWayList = this.moneyAppleInfo.data.JSFSlist;
        Log.printObj(CloseAccountTabPage.TAG,"辅助申请单信息=====",this.payWayList);

        this.payWayList.map((item) => {
            if (item.JieSuanFS == '3') {
                this.zzList = item.Content;
            }
            if (item.JieSuanFS == '4') {
                this.gwkList = item.Content;
            }
        });
        this.payWayList.map((v,i)=>{
            this.parameterJson();
            this.list[i].option =v.JieSuanFS;
            this.list[i].feeLabel=v.JieSuanJE;
            this.appleFee =v.JieSuanJE;
            if(v.JieSuanFS=="3"){
                this.list[i].zzLabel[0].Value =v.ShouKuanFZHM;
                this.list[i].zzLabel[1].Value=v.KaiHuH;
                this.list[i].zzLabel[2].Value=v.ZhangHao;
            }
            if(v.JieSuanFS=="4"){
                this.list[i].gwkLabel[0].Value =v.GongWuKH;
                this.list[i].gwkLabel[1].Value=v.XiaoFeiRQ;
                this.list[i].gwkLabel[2].Value=v.JiZhangRQ;
                this.list[i].gwkLabel[3].Value=v.HuanKuanRQ;
                this.list[i].gwkLabel[4].Value=v.BeiZhu;
            }
        });*/
    }
    getCloseFeeList() {
        this.sys.getAccountInfo({}).subscribe((res: any) => {
            if (res.msgCode == "1" &&  res.list.length>0) {
                this.payWayList = res.list;
                this.payWayList.map((item) => {
                    if (item.MingCheng == '转账') {
                        this.zzList = item.Content;
                    }
                    if (item.MingCheng == '公务卡') {
                        this.gwkList = item.Content;
                    }
                });
               /* if(this.moneyAppleBool){
                    this.moneyApplyDataFun();
                    return;
                }*/
                if (this.editBool) {
                    this.parameterEditJson();
                }else {
                    this.parameterJson();

                }
            }
        }, error => {
            this.showError('网络连接错误')
        })
    }

    ionViewDidLoad() {
        console.log('ionViewDidLoad CloseAccountTabPage');
        //this.payWayList = JSON.parse(localStorage.getItem('payWayList'));
        this.addBtnShow.emit(true);
    }

    getCloseWayList(list) {
        let alert = this.alertCtrl.create();
        alert.setTitle('结算方式');
        this.payWayList.forEach((value, index) => {
            alert.addInput({
                type: 'radio',
                label: value.MingCheng,
                value: value.BianMa,
                checked: index == 0 ? true : false
            });
        });
        alert.addButton('取消');
        alert.addButton({
            text: '确定',
            handler: data => {

            }
        });
        alert.present();
    }

    changeAddStatus(value) {
        this.addBtnShow = value;
    }
    parameterEditJson(){

        this.editInfo.JieSuanXX.map((v,i)=>{
            this.parameterJson();
            this.list[i].option =this.JieSuanFSFun(v.JieSuanFS);
            this.list[i].feeLabel=v.JieSuanJE;
            this.appleFee =v.JieSuanJE;
            if(v.JieSuanFS=="转账"){
                this.list[i].zzLabel[0].Value =v.ShouKuanFZHM;
                this.list[i].zzLabel[1].Value=v.KaiHuH;
                this.list[i].zzLabel[2].Value=v.ZhangHao;
            }
            if(v.JieSuanFS=="公务卡"){
                this.list[i].gwkLabel[0].Value =v.GongWuKH;
                this.list[i].gwkLabel[1].Value=v.XiaoFeiRQ;
                this.list[i].gwkLabel[2].Value=v.JiZhangRQ;
                this.list[i].gwkLabel[3].Value=v.HuanKuanRQ;
                this.list[i].gwkLabel[4].Value=v.BeiZhu;
            }
        });
    }
    JieSuanFSFun(val){
        if(val=="转账"){
            return "3"
        }else if(val=="公务卡"){
            return "4"
        }
        else if(val=="现金"){
            return "1"
        }else if(val=="支票"){
            return "2"
        }
    }
    parameterJson() {
        if (Number(this.appleFee) == 0) {
            this.appleFee = '';
        }
        this.list.push({
            option: this.payWayList[0].BianMa,
            feeLabel: this.newValFee,
            zzLabel: [
                {Key: 'ShouKuanFZHM', Value: ''},
                {Key: 'KaiHuH', Value: ''},
                {Key: 'ZhangHao', Value: ''}],
            gwkLabel: [
                {Key: 'GongWuKH', Value: ''},
                {Key: 'XiaoFeiRQ', Value: ''},
                {Key: 'JiZhangRQ', Value: ''},
                {Key: 'HuanKuanRQ', Value: ''},
                {Key: 'BeiZhu', Value: ''}]
        });
    }

    addHandler(item) {
        this.parameterJson();
    }

    deleteHandler(item, i) {
        if (this.list.length >= 2) {
            this.list.splice(i, 1);
        } else {
            this.showError('继续删除无法添加新的内容');
        }
    }

    isValNull() {
        this.isNullBool = false;
        for (let i = 0; i < this.list.length; i++) {
            if (this.list[i].option == '') {
                this.showError('请选择结算方式');
                this.isNullBool = true;
                break;
            }
            if (this.list[i].option == "3") {
                for (let n = 0; n < this.list[i].zzLabel.length; n++) {
                    if (this.list[i].zzLabel[n].Value == '') {
                        this.showError('填写的内容不完整');
                        this.isNullBool = true;
                        break;
                    }
                }
            }
            if (this.list[i].option == "4") {
                for (let m = 0; m < this.list[i].gwkLabel.length; m++) {
                    if (this.list[i].gwkLabel[m].Value == '') {
                        this.showError('填写的内容不完整');
                        this.isNullBool = true;
                        break;
                    }
                }
            }

        }
        return this.isNullBool;
    }

    complete() {
        if(!this.isFristBool){
            this.isFristBool=true;
            setTimeout(()=>{
                this.isFristBool=false;
            },6000);
            if (!this.isValNull()) {
                if(!this.isClickBool){
                    this.isClickBool =true;
                    this.closeWayInfo();
                }

            }
        }

    }

    //结账信息
    async closeWayInfo() {
        this.newCloseWay.splice(0, this.newCloseWay.length);
        for (let i = 0; i < this.list.length; i++) {
            if (this.list[i].option == "3") {
                this.newCloseWay.push({
                    JieSuanFS: this.list[i].option,
                    JieSuanJE: this.list[i].feeLabel,
                    Content: this.list[i].zzLabel
                })
            } else if (this.list[i].option == "4") {
                this.newCloseWay.push({
                    JieSuanFS: this.list[i].option,
                    JieSuanJE: this.list[i].feeLabel,
                    Content: this.list[i].gwkLabel
                })
            } else {
                this.newCloseWay.push({
                    JieSuanFS: this.list[i].option,
                    JieSuanJE: this.list[i].feeLabel,
                    Content: []
                })
            }
        }
        Log.printObj(CloseAccountTabPage.TAG, 'new list parameter', this.newCloseWay);
         this.getFlowInfo();
    }

    delcommafy(num) {
        num = num.toString();
        num = num.replace(/[ ]/g, "");//去除空格  
        num = num.replace(/,/gi, '');
        return Number(num);
    }

    getFlowInfo() {
        if (this.keyongFee != '') {
            if (this.delcommafy(this.appleFee) > this.delcommafy(this.keyongFee)) {
                this.showError('报销金额不能大于指标余额');
                this.isClickBool =false;
                return;
            }
        }

        if (this.sxFee != '') {
            if (this.delcommafy(this.appleFee) > this.delcommafy(this.sxFee)) {
                this.showError('报销金额不能大于费用限额');
                this.isClickBool =false;
                return;
            }
        }

        let data = {
            YuSuanND: UserManager.getInstance().user.year,
            DanWeiBH: UserManager.getInstance().user.unitId,
            ZhiChuSX: this.getApplyInfo.ZhiChuSX,
            ZhiBiao: this.getApplyInfo.ZhiBiaoBH,
            DanJuLX: this.getApplyInfo.BaoXiaoLX
        };
        this.sys.getFlowInfo(data).subscribe((res: any) => {
            if (res.msgCode == "1") {
                this.flowList = res.list;
                if (this.flowList.length == 1) {
                    this.applyHandler(this.flowList[0].BianHao);
                } else if (this.flowList.length > 1) {
                    this.bxTypeHander();
                }
            }
        }, error => {

        })
    }

    bxTypeHander() {
        let alert = this.alertCtrl.create();
        alert.setTitle('流程名称');
        this.flowList.forEach((value) => {
            alert.addInput({
                type: 'radio',
                label: value.MingCheng,
                value: value.BianHao
            });
        });
        alert.addButton('取消');
        alert.addButton({
            text: '确定',
            handler: id => {
                this.applyHandler(id);
            }
        });
        alert.present();
    }

    applyHandler(id) {
        this.isClickBool =false;
        let data: any = {
            GangWeiBH: UserManager.getInstance().user.postId,
            FlowId: id,
            BiaoXiaoBH: this.getApplyInfo.BiaoXiaoBH,
            BaoXiaoLX: this.getApplyInfo.BaoXiaoLX,
            ZhiBiaoBH: this.getApplyInfo.ZhiBiaoBH,
            ShenQingR: this.getApplyInfo.ShenQingR,
            NianDu: this.getApplyInfo.NianDu,
            ShenQingDW: this.getApplyInfo.ShenQingDW,
            ShenQingBM: this.getApplyInfo.ShenQingBM,
            ShenQingJE: this.appleFee,
            BaoXiaoR: this.getApplyInfo.BaoXiaoR,
            BaoXiaoBM: this.getApplyInfo.BaoXiaoBM,
            BaoXiaoRQ: this.getApplyInfo.BaoXiaoRQ,
            BaoXiaoSY: this.getApplyInfo.BaoXiaoSY,
            ZhiChuSX: this.getApplyInfo.ZhiChuSX,
            BeiZhu: this.getApplyInfo.BeiZhu,
            DuiYingDJ: this.getApplyInfo.DuiYingDJ,
            KeYongYE: this.getApplyInfo.KeYongYE,
            HeTongJD: this.getApplyInfo.HeTongJD,
            FuJianXX: this.getFileInfo,
            ZhiChuXX: this.getApplyDetails,
            FuZhuSX: this.getAssistInfo,
            JieSuanXX: this.newCloseWay
        };
        this.sys.getApplyDetailUrl(data).subscribe(async (res: any) => {
            if (res.msgCode == "1") {
                //this.payWayList = res;
                //this.showToast('已申请');
                await SLLocalStorageUtils.getInstance().clearFileInfo();
                await SLLocalStorageUtils.getInstance().clearApply();
                await SLLocalStorageUtils.getInstance().clearApplyDetails();
                await SLLocalStorageUtils.getInstance().clearAssist();
                UserManager.getInstance().user.djId = '';
                this.app.getRootNav().setRoot(TabsPage);
                ApplyStoreSLS.getInstance().destroy();
            } else {
                this.showToast(res.msg);
            }
        }, error => {
            this.showToast('申请失败');
        })
    }

    ionViewDidLeave() {
        ApplyStoreSLS.getInstance().closeAccountList = this.list;
        ApplyStoreSLS.getInstance().closeWayList = this.payWayList;
        ApplyStoreSLS.getInstance().gwkList = this.gwkList;
        ApplyStoreSLS.getInstance().zzList = this.zzList;
    }
}
